#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->widget->setStyleSheet("border: 2px solid black;");
    ui->label_4->setStyleSheet(" QLabel#label_4 {border-radius: 25px; background-color: black;}");
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
    if (clickedWidget && clickedWidget != ui->centralwidget) {
        QPoint currentGlobalPos = mapToGlobal(event->pos());
        QPoint newButtonGlobalPos = currentGlobalPos - offset;

        QWidget *parent = clickedWidget->parentWidget();
        QPoint newButtonLocalPos = parent->mapFromGlobal(newButtonGlobalPos);

        // 获取父容器的有效范围
        QRect parentRect = parent->rect();  // 父容器的局部坐标系范围（0,0 到 width, height）

        // 获取控件自身的大小
        QSize widgetSize = clickedWidget->size();

        // 限制左上角 x 不小于 0，不大于父容器宽度 - 控件宽度
        int x = qBound(0, newButtonLocalPos.x(), parentRect.width() - widgetSize.width());
        // 限制左上角 y 不小于 0，不大于父容器高度 - 控件高度
        int y = qBound(0, newButtonLocalPos.y(), parentRect.height() - widgetSize.height());

        clickedWidget->move(x,y);
    }
    QMainWindow::mouseMoveEvent(event);
}

void MainWindow::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        QPoint globalPos = mapToGlobal(event->pos());
        clickedWidget = QApplication::widgetAt(globalPos);

        if (clickedWidget) {
            QPoint widgetLocalPos = clickedWidget->mapFromGlobal(globalPos);
            offset = widgetLocalPos;  // 记录偏移量，用于拖动时计算位置
        }

        QMainWindow::mousePressEvent(event);
    }
}


void MainWindow::mouseReleaseEvent(QMouseEvent *event)
{
    if(clickedWidget)
    {
        clickedWidget = nullptr;
    }
    QMainWindow::mouseReleaseEvent(event);
}

void MainWindow::closeEvent(QCloseEvent * event){
    auto ret = QMessageBox::question(this,"是否退出","你真的要离开我吗？",QMessageBox::Ok|QMessageBox::Cancel,QMessageBox::Cancel);
    if (ret == QMessageBox::Ok) {
        // 用户确认退出，允许窗口关闭
        event->accept();
    } else {
        // 用户取消退出，阻止窗口关闭
        event->ignore();
    }
}

void MainWindow::enterEvent(QEvent *event)
{
    qDebug() << "进入窗口边界";
}

void MainWindow::leaveEvent(QEvent *event)
{
    qDebug() << "退出窗口边界";
}

void MainWindow::keyPressEvent(QKeyEvent *event)
{
    if(event->key() == Qt::Key_L)
    {
        qDebug() <<" l";
    }
    qDebug() << event->text();
}

void MainWindow::focusInEvent(QFocusEvent *e)
{
    //光标聚集不了，只有文本框那种才能让光标聚集，但是mainwindow没有能让光标聚集的办法，所以意义不大
    qDebug() <<"鼠标光标进入窗口";
}

void MainWindow::focusOutEvent(QFocusEvent *e)
{
    qDebug() <<"鼠标光标退出窗口";
}
